package cn.edu.hit.core.message;

import com.fasterxml.jackson.databind.JavaType;
import cn.edu.hit.core.Document;

import java.util.Collections;
import java.util.List;
import java.util.Random;

/**
 * 对随机的数据进行生成
 */
public final class RandomAdapter extends MessageAdapterHelper2 {
    @Override
    public boolean accept(String type) {
        return "Random".equalsIgnoreCase(type);
    }

    private static final Random random = new Random();
    private static JavaType doubleListType = mapper.getTypeFactory().constructParametricType(List.class, Double.TYPE);

//    @Override
//    public Stream<Map> service(Long timestamp) {
//        return configureMap.entrySet().parallelStream().map(entry->{
//            Document result = new Document();
//            String id = entry.getKey();
//            Document configure = (Document) entry.getValue();
//
//            result.put(PORT_ID,id);
//            result.put("portName",configure.getString("portName"));
////            result.setDimension(configure.getDimension());
////            result.setMachineId(configure.getMachineId());
////            result.setName(configure.getName());
//
//            String argString = configure.getString(DATA_SOURCE_ARGS);
//            double minVal = Double.parseDouble(configure.getString(MAX_VALUE));
//            double maxVal = Double.parseDouble(configure.getString(MIN_VALUE));
//            List<Double> value = Collections.emptyList();
//            try {
//                value = mapper.readValue(argString,doubleListType);
//                if(value!=null && value.size()==2){
//                    minVal = value.get(0);
//                    maxVal = value.get(1);
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            double val = minVal + (maxVal-minVal)*random.nextDouble();
//            result.put(VALUE,Collections.singletonList(val));
//            result.put(TIMESTAMP,timestamp);
//            return result;
//        });
//    }

    @Override
    protected Object getValue(Object stringMap, String id, Document configure) {
        String argString = configure.getString(DATA_SOURCE_ARGS);
        double minVal = Double.parseDouble(configure.getString(MAX_VALUE));
        double maxVal = Double.parseDouble(configure.getString(MIN_VALUE));
        try {
            List<Double> value = mapper.readValue(argString, doubleListType);
            if (value != null && value.size() == 2) {
                minVal = value.get(0);
                maxVal = value.get(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        double val = minVal + (maxVal - minVal) * random.nextDouble();
        return Collections.singletonList(val);
    }
}
